package com.huluobo.lib_base

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.huluobo.lib_base.entity.LocalEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import java.io.File

/**
 *  Created by LC on 2025/1/13.
 */
abstract class BaseViewModel<uiIntent : UIIntent> : ViewModel() {

    //存放管理意图的管道
    private val _uiIntent = Channel<UIIntent>(Channel.UNLIMITED)

    //可变的状态,用于更新UI
    private var _state = MutableStateFlow<UIState>(UIState.onLoading)
    val state: StateFlow<UIState>
        get() = _state

    init {
        viewModelScope.launch {
            _uiIntent.receiveAsFlow().collect {
                handleIntent(it)
            }
        }
    }

    //处理意图
    abstract fun handleIntent(intent: UIIntent)

    //发送意图
    fun sendIntent(intent: UIIntent) {
        viewModelScope.launch {
            _uiIntent.send(intent)
        }
    }

    //网络请求
    fun httpRequest(request: Flow<Res<Any>>, type: HttpType = HttpType.DEFAULT) {
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    Log.e("TagA", "error:${it.message}")
                }.collect {
                    if (it.code == 0) {
                        _state.value = UIState.onSuccess(it.data, type)
                    } else {
                        _state.value = UIState.onError(it.msg)
                    }
                }
        }
    }

    //下载文件
    fun download(url: String, file: File) {
        viewModelScope.launch {
            DownloadUtil.download(url, file)
                .flowOn(Dispatchers.IO)
                .catch {
                    Log.e("TagA", "error:${it.message}")
                }.collect {
                    _state.value = it
                }
        }
    }

    //扫描本地文件
    fun scanFile(file: File) {
        viewModelScope.launch {
            try {
                val files = file.listFiles()
                val list = mutableListOf<LocalEntity>()
                for (file in files) {
                    list.add(LocalEntity(file.name, file.absolutePath))
                }
                _state.value = UIState.onSuccess(list)
            } catch (e: Exception) {
                _state.value = UIState.onError(e.message.toString())
            }
        }
    }
}